package com.southwind.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.southwind.common.Cache;
import com.southwind.common.NewsPageModel;
import com.southwind.common.ResultObj;
import com.southwind.entity.SysNews;
import com.southwind.entity.SysUser;
import com.southwind.service.SysNewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author admin
 * @since 2024-05-28
 */
@RestController
@RequestMapping("/news")
public class SysNewsController {

    @Autowired
    private SysNewsService newsService;

    @GetMapping("/load")
    public Map load(NewsPageModel newsPageModel){
        QueryWrapper<SysNews> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(newsPageModel.getTitle()), "title", newsPageModel.getTitle());
        Page<SysNews> page = new Page<>(newsPageModel.getPage(), newsPageModel.getLimit());
        Page<SysNews> resultPage = this.newsService.page(page, queryWrapper);
        return ResultObj.resultData(resultPage.getRecords(), resultPage.getTotal());
    }

    @PostMapping("/add")
    public ResultObj add(@RequestBody SysNews news){
        SysUser user = (SysUser) Cache.get("user");
        news.setOpername(user.getRealname());
        boolean save = this.newsService.save(news);
        if(save) return ResultObj.NEWS_ADD_SUCCESS;
        return ResultObj.NEWS_ADD_ERROR;
    }

    @PostMapping("/update")
    public ResultObj update(@RequestBody SysNews news){
        boolean updateById = this.newsService.updateById(news);
        if(updateById) return ResultObj.NEWS_UPDATE_SUCCESS;
        return ResultObj.NEWS_UPDATE_ERROR;
    }

    @DeleteMapping("/delete")
    public ResultObj delete(String id){
        boolean removeById = this.newsService.removeById(id);
        if(removeById) return ResultObj.NEWS_DELETE_SUCCESS;
        return ResultObj.NEWS_DELETE_ERROR;
    }

}

